# import sys
# import threading
# from pympler import tracker,summary,muppy
# #memory_tracker=tracker.SummaryTracker()
import gc
import os
# import shutil
# from PyQt5.QtCore import pyqtSignal
from threading import Thread

from PyQt5.QtChart import QChart, QLineSeries, QValueAxis, QChartView
# from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QMessageBox
# from PyQt5.QtGui import *
from numba import jit
from TDC20201016 import *
from cursorsetting import *
from Expsetting import *
from PyQt5.Qt import *
# from pyqtgraph import PlotWidget
# from PyQt5 import QtCore
import numpy as np
import pyqtgraph as pq
import datetime
from PyQt5 import QtCore, QtGui

# import matplotlib
# import matplotlib.pyplot as plt
# import time
# from collections import Counter


try:
    import QuTAG
except:
    print("Time Tagger wrapper QuTAG.py is not in the search path.")
qutag = QuTAG.QuTAG()


@jit
def cal(length, threadnumber, data1, data2,  cursor_1_1_e, cursor_1_2_e, cursor_1_1_l, cursor_1_2_l, cursor_1_1_f,
        cursor_1_2_f, cursor_2_1_e, cursor_2_2_e, cursor_2_1_l, cursor_2_2_l, cursor_2_1_f, cursor_2_2_f, cursor_3_1_e,
        cursor_3_2_e, cursor_3_1_l, cursor_3_2_l, cursor_3_1_f, cursor_3_2_f, cursor_4_1_e, cursor_4_2_e, cursor_4_1_l,
        cursor_4_2_l, cursor_4_1_f, cursor_4_2_f):
    data4 = np.zeros(shape=(100000,2))
    data5 = np.zeros(shape=(100000,2))
    data6 = np.zeros(shape=(100000,2))
    data7 = np.zeros(shape=(100000,2))
    sweeps = 0
    det = np.zeros(shape=(4, 3))
    count = np.zeros(shape=(4, 3))
    coin = np.zeros(shape=(6, 6))
    trigger_time = 0
    aa = np.arange(int(threadnumber*length/10), int((threadnumber+1)*length/10)-1, 1)
    for i in aa:  # np.arange(0, len(data1), 1):
        if data2[i] == 4:
            sweeps = sweeps + 1
            trigger_time = 0#data1[i]
            if det[0][0] != 0:
                if det[2][0] != 0:
                    coin[0][0] = coin[0][0] + 1
                if det[2][1] != 0:
                    coin[0][1] = coin[0][1] + 1
                if det[2][2] != 0:
                    coin[0][2] = coin[0][2] + 1
                if det[3][0] != 0:
                    coin[0][3] = coin[0][3] + 1
                if det[3][1] != 0:
                    coin[0][4] = coin[0][4] + 1
                if det[3][2] != 0:
                    coin[0][5] = coin[0][5] + 1
            if det[0][1] != 0:
                if det[2][0] != 0:
                    coin[1][0] = coin[1][0] + 1
                if det[2][1] != 0:
                    coin[1][1] = coin[1][1] + 1
                if det[2][2] != 0:
                    coin[1][2] = coin[1][2] + 1
                if det[3][0] != 0:
                    coin[1][3] = coin[1][3] + 1
                if det[3][1] != 0:
                    coin[1][4] = coin[1][4] + 1
                if det[3][2] != 0:
                    coin[1][5] = coin[1][5] + 1
            if det[0][2] != 0:
                if det[2][0] != 0:
                    coin[2][0] = coin[2][0] + 1
                if det[2][1] != 0:
                    coin[2][1] = coin[2][1] + 1
                if det[2][2] != 0:
                    coin[2][2] = coin[2][2] + 1
                if det[3][0] != 0:
                    coin[2][3] = coin[2][3] + 1
                if det[3][1] != 0:
                    coin[2][4] = coin[2][4] + 1
                if det[3][2] != 0:
                    coin[2][5] = coin[2][5] + 1
            if det[1][0] != 0:
                if det[2][0] != 0:
                    coin[3][0] = coin[3][0] + 1
                if det[2][1] != 0:
                    coin[3][1] = coin[3][1] + 1
                if det[2][2] != 0:
                    coin[3][2] = coin[3][2] + 1
                if det[3][0] != 0:
                    coin[3][3] = coin[3][3] + 1
                if det[3][1] != 0:
                    coin[3][4] = coin[3][4] + 1
                if det[3][2] != 0:
                    coin[3][5] = coin[3][5] + 1
            if det[1][1] != 0:
                if det[2][0] != 0:
                    coin[4][0] = coin[4][0] + 1
                if det[2][1] != 0:
                    coin[4][1] = coin[4][1] + 1
                if det[2][2] != 0:
                    coin[4][2] = coin[4][2] + 1
                if det[3][0] != 0:
                    coin[4][3] = coin[4][3] + 1
                if det[3][1] != 0:
                    coin[4][4] = coin[4][4] + 1
                if det[3][2] != 0:
                    coin[4][5] = coin[4][5] + 1
            if det[1][2] != 0:
                if det[2][0] != 0:
                    coin[5][0] = coin[5][0] + 1
                if det[2][1] != 0:
                    coin[5][1] = coin[5][1] + 1
                if det[2][2] != 0:
                    coin[5][2] = coin[5][2] + 1
                if det[3][0] != 0:
                    coin[5][3] = coin[5][3] + 1
                if det[3][1] != 0:
                    coin[5][4] = coin[5][4] + 1
                if det[3][2] != 0:
                    coin[5][5] = coin[5][5] + 1
            else:
                pass
            det = np.zeros(shape=(4, 3))
        elif data2[i] == 1:
            data1[i] = data1[i] - trigger_time
            if -1 < data1[i] < 100000:
                x = int(data1[i])
                data4[x][1] = data4[x][1] + 1
            if cursor_1_1_e < data1[i] < cursor_1_2_e:
                det[0][0] = det[0][0] + 1
                count[0][0] = count[0][0] + 1
            elif cursor_1_1_l < data1[i] < cursor_1_2_l:
                det[0][1] = det[0][1] + 1
                count[0][1] = count[0][1] + 1
            elif cursor_1_1_f < data1[i] < cursor_1_2_f:
                det[0][2] = det[0][2] + 1
                count[0][2] = count[0][2] + 1
            else:
                pass
        elif data2[i] == 2:
            data1[i] = data1[i] - trigger_time
            if 0 < data1[i] < 100000:
                x = int(data1[i])
            if cursor_2_1_e < data1[i] < cursor_2_2_f:
                data5[x][1] = data5[x][1] + 1
            else:
                pass
            if cursor_2_1_e < data1[i] < cursor_2_2_e:
                det[1][0] = det[1][0] + 1
                count[1][0] = count[1][0] + 1
            elif cursor_2_1_l < data1[i] < cursor_2_2_l:
                det[1][1] = det[1][1] + 1
                count[1][1] = count[1][1] + 1
            elif cursor_2_1_f < data1[i] < cursor_2_2_f:
                det[1][2] = det[1][2] + 1
                count[1][2] = count[1][2] + 1
            else:
                pass
        elif data2[i] == 3:
            data1[i] = data1[i] - trigger_time
            if 0 < data1[i] < 100000:
                x = int(data1[i])
            if cursor_3_1_e < data1[i] < cursor_3_2_f:
                data6[x][1] = data6[x][1] + 1
            else:
                pass
            if cursor_3_1_e < data1[i] < cursor_3_2_e:
                det[2][0] = det[2][0] + 1
                count[2][0] = count[2][0] + 1
            elif cursor_3_1_l < data1[i] < cursor_3_2_l:
                det[2][1] = det[2][1] + 1
                count[2][1] = count[2][1] + 1
            elif cursor_3_1_f < data1[i] < cursor_3_2_f:
                det[2][2] = det[2][2] + 1
                count[2][2] = count[2][2] + 1
            else:
                pass
        elif data2[i] == 64:
            data1[i] = data1[i] - trigger_time
            if 0 < data1[i] < 100000:
                x = int(data1[i])
            if cursor_4_1_e < data1[i] < cursor_4_2_f:
                data7[x][1] = data7[x][1] + 1
            if cursor_4_1_e < data1[i] < cursor_4_2_e:
                det[3][0] = det[3][0] + 1
                count[3][0] = count[3][0] + 1
            elif cursor_4_1_l < data1[i] < cursor_4_2_l:
                det[3][1] = det[3][1] + 1
                count[3][1] = count[3][1] + 1
            elif cursor_4_1_f < data1[i] < cursor_4_2_f:
                det[3][2] = det[3][2] + 1
                count[3][2] = count[3][2] + 1
            else:
                pass
        else:
            pass

    return sweeps, count, coin, data4, data5, data6, data7  # , hist_ch1

class MyThread(Thread):
    def __init__(self, func, args):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.results = self.func(*self.args)

    def get_result(self):
        try:
            return self.results
        except Exception:
            return None

class SetExpTime(QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super(SetExpTime, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("Set ExpTime")
        self.Button_SetExpTime_ok.clicked.connect(self.ExpTime)
        self.Set_Exp_Time.setText('20')
        self.Set_Exp_ExposureTime.setText('1')

    def ExpTime(self):
        self.ExpTime_set = self.Set_Exp_Time.text()
        self.ExposureTime_set = self.Set_Exp_ExposureTime.text()
        self.Set_Exp_Time.setText(self.ExpTime_set)
        self.close()
        return self.ExpTime_set, self.ExposureTime_set


class SetCursor(QDialog, Ui_CursorSetting):
    def __init__(self, parent=None):
        super(SetCursor, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("Set Cursor")
        self.Set_Cursorsetting_ok.clicked.connect(self.setcursor)

    def setcursor(self):
        cursor_1_1 = self.Set_Cursor1_Channel1.text()
        cursor_1_2 = self.Set_Cursor2_Channel1.text()
        cursor_2_1 = self.Set_Cursor1_Channel2.text()
        cursor_2_2 = self.Set_Cursor2_Channel2.text()
        cursor_3_1 = self.Set_Cursor1_Channel3.text()
        cursor_3_2 = self.Set_Cursor2_Channel3.text()
        self.close()
        return cursor_1_1, cursor_1_2, cursor_2_1, cursor_2_2, cursor_3_1, cursor_3_2


class Window(QMainWindow, Ui_MainWindow):
    # signal1 = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.stop_trigger = 0
        self.Time_Waiting_GetTimestamps = 1

        # 测量时间初始值
        self.ExpTimeSetting = 10000
        self.ExposureTimeSetting = 500  # ms

        # 光标设置
        self.input_chart_range_1_1 = 0
        self.input_chart_range_1_2 = 100000
        self.input_chart_range_2_1 = 0
        self.input_chart_range_2_2 = 100000
        self.input_chart_range_3_1 = 0
        self.input_chart_range_3_2 = 100000
        self.input_chart_range_4_1 = 0
        self.input_chart_range_4_2 = 100000
        self.chart_range_1_1.setText('56000')
        self.chart_range_1_2.setText('56500')
        self.chart_range_2_1.setText('55800')
        self.chart_range_2_2.setText('56300')
        self.chart_range_3_1.setText('54000')
        self.chart_range_3_2.setText('54500')
        self.chart_range_4_1.setText('52284')
        self.chart_range_4_2.setText('52421')
        self.channel1_cursor1 = 15435
        self.channel1_cursor2 = 15489
        self.channel2_cursor1 = 51069
        self.channel2_cursor2 = 51128
        self.channel3_cursor1 = 50000
        self.channel3_cursor2 = 50070
        self.cursor_1_1_f.setText('56295')
        self.cursor_1_2_f.setText('56345')
        self.cursor_2_1_f.setText('56075')
        self.cursor_2_2_f.setText('56125')
        self.cursor_3_1_f.setText('54185')
        self.cursor_3_2_f.setText('54235')
        self.cursor_1_1_e.setText('56045')
        self.cursor_1_2_e.setText('56095')
        self.cursor_2_1_e.setText('55825')
        self.cursor_2_2_e.setText('55875')
        self.cursor_1_1_l.setText('56170')
        self.cursor_1_2_l.setText('56220')
        self.cursor_2_1_l.setText('55945')
        self.cursor_2_2_l.setText('55995')
        self.cursor_3_1_e.setText('53935')
        self.cursor_3_1_l.setText('53985')
        self.cursor_3_2_l.setText('54110')
        self.cursor_4_1_e.setText('19147')
        self.cursor_4_2_e.setText('19217')
        self.cursor_4_1_l.setText('25974')
        self.cursor_3_2_e.setText('50405')
        self.cursor_4_2_l.setText('26044')
        self.cursor_4_1_f.setText('25974')
        self.cursor_4_2_f.setText('26044')

        self.filewritestop = None
        self.path = os.getcwd()

        self.Time_Start = datetime.datetime.now()
        self.Button_Start.clicked.connect(self.starting)
        self.Button_Stop.clicked.connect(self.stopping)
        self.action_Exptime.triggered.connect(self.SetExpTime)
        # self.Action_Cursor.triggered.connect(self.SetCursor)
        self.ViewChart_Range_set.clicked.connect(self.SetChartrange)
        self.Cursor_Set.clicked.connect(self.SetCursor)

    def SetExpTime(self):
        self.SetExpTimeWindow = SetExpTime()
        self.SetExpTimeWindow.exec_()
        self.exptime = self.SetExpTimeWindow.ExpTime()
        self.ExpTimeSetting = int(self.exptime[0])
        self.ExposureTimeSetting = int(float(self.exptime[1]) * 1000)

    def SetCursor(self):
        self.channel1_cursor1_f = float(self.cursor_1_1_f.text())
        self.channel1_cursor2_f = float(self.cursor_1_2_f.text())
        self.channel2_cursor1_f = float(self.cursor_2_1_f.text())
        self.channel2_cursor2_f = float(self.cursor_2_2_f.text())
        self.channel3_cursor1_f = float(self.cursor_3_1_f.text())
        self.channel3_cursor2_f = float(self.cursor_3_2_f.text())
        self.channel4_cursor1_f = float(self.cursor_4_1_f.text())
        self.channel4_cursor2_f = float(self.cursor_4_2_f.text())
        self.channel1_cursor1_e = float(self.cursor_1_1_e.text())
        self.channel1_cursor2_e = float(self.cursor_1_2_e.text())
        self.channel3_cursor1_e = float(self.cursor_3_1_e.text())
        self.channel3_cursor2_e = float(self.cursor_3_2_e.text())
        self.channel3_cursor1_l = float(self.cursor_3_1_l.text())
        self.channel3_cursor2_l = float(self.cursor_3_2_l.text())
        self.channel4_cursor1_e = float(self.cursor_4_1_e.text())
        self.channel4_cursor2_e = float(self.cursor_4_2_e.text())
        self.channel4_cursor1_l = float(self.cursor_4_1_l.text())
        self.channel4_cursor2_l = float(self.cursor_4_2_l.text())
        self.channel1_cursor1_l = float(self.cursor_1_1_l.text())
        self.channel1_cursor2_l = float(self.cursor_1_2_l.text())
        self.channel2_cursor1_e = float(self.cursor_2_1_e.text())
        self.channel2_cursor2_e = float(self.cursor_2_2_e.text())
        self.channel2_cursor1_l = float(self.cursor_2_1_l.text())
        self.channel2_cursor2_l = float(self.cursor_2_2_l.text())

    def SetChartrange(self):
        self.input_chart_range_1_1 = float(self.chart_range_1_1.text())
        self.input_chart_range_1_2 = float(self.chart_range_1_2.text())
        self.input_chart_range_2_1 = float(self.chart_range_2_1.text())
        self.input_chart_range_2_2 = float(self.chart_range_2_2.text())
        self.input_chart_range_3_1 = float(self.chart_range_3_1.text())
        self.input_chart_range_3_2 = float(self.chart_range_3_2.text())
        self.input_chart_range_4_1 = float(self.chart_range_4_1.text())
        self.input_chart_range_4_2 = float(self.chart_range_4_2.text())

    def stopping(self):
        self.stop_trigger = 1

    def starting(self):
        # self.chart_ch = QChart()
        self.filewritestop = 0
        self.count_sweeps = 0
        self.counts = np.zeros(shape=(4, 3))
        self.pro = np.zeros(shape=(4, 3))
        self.coin = np.zeros(shape=(6, 6))
        self.histname_ch1 = None
        self.histname_ch2 = None
        self.histname_ch3 = None
        self.histname_ch4 = None
        self.saveindex = self.save_index.text()

        self.file_originnaldata = self.path + '\DataRecording' + '\originaldata.txt'
        self.histname_ch1 = self.path + '\DataRecording' + '\hist_ch1.CSV'
        if os.path.exists(self.histname_ch1):  # 如果文件存在
            os.remove(self.histname_ch1)
        else:
            pass  # 则返回文件不存在
        self.histname_ch2 = self.path + '\DataRecording' + '\hist_ch2.CSV'
        if os.path.exists(self.histname_ch2):  # 如果文件存在
            os.remove(self.histname_ch2)
        else:
            pass  # 则返回文件不存在
        self.histname_ch3 = self.path + '\DataRecording' + '\hist_ch3.CSV'
        if os.path.exists(self.histname_ch3):  # 如果文件存在
            os.remove(self.histname_ch3)
        else:
            pass  # 则返回文件不存在
        self.histname_ch4 = self.path + '\DataRecording' + '\hist_ch4.CSV'
        if os.path.exists(self.histname_ch4):  # 如果文件存在
            os.remove(self.histname_ch4)
        else:
            pass  # 则返回文件不存在
        self.filename_result = self.path + '\DataRecording' + '\DataRecording.txt'
        if os.path.exists(self.filename_result):  # 如果文件存在
            os.remove(self.filename_result)
        else:
            pass  # 则返回文件不存在
        self.filename_result_sum = self.path + '\DataRecording' + '\DataRecording_sum.txt'
        # if os.path.exists(self.filename_result_sum):  # 如果文件存在
        # os.remove(self.filename_result_sum)
        # else:
        # pass  # 则返回文件不存在
        open(self.file_originnaldata, 'w')
        qutag.writeTimestamps(self.file_originnaldata, qutag.FILEFORMAT_ASCII)

        # initinal
        self.stop_trigger = 0
        self.count_sweeps = 1
        self.det2 = 0
        self.det3 = 0
        self.Result_Counts_2 = 0
        self.Result_Counts_3 = 0
        self.Result_Counts_Coin23 = 0
        # 0830
        self.hist_ch1 = np.zeros(shape=(100000, 2))
        self.hist_ch2 = np.zeros(shape=(100000, 2))
        self.hist_ch3 = np.zeros(shape=(100000, 2))
        self.hist_ch4 = np.zeros(shape=(100000, 2))
        for i in range(100000):
            self.hist_ch1[i][0] = i
            self.hist_ch2[i][0] = i
            self.hist_ch3[i][0] = i
            self.hist_ch4[i][0] = i
        self.hist_ch1_0 = self.hist_ch1.T[0]
        self.hist_ch1_1 = self.hist_ch1.T[1]
        self.Time_Exp_Start = datetime.datetime.now()

        self.Result_Timestamps = qutag.getLastTimestamps(True)
        print('starttime', datetime.datetime.now())
        if self.stop_trigger == 0:
            self.timer = pq.QtCore.QTimer()
            self.timer.timeout.connect(self.update_data)
            self.timer.start(self.ExposureTimeSetting)  # shezhiTDCduqujiange
        else:
            pass
        # for i in range(self.ExpTimeSetting):
        #     time.sleep(2)
        #     self.signal1.connect(self.update_data)
        #     self.signal1.emit()

    def update_data(self):
        thread = None
        Time_Exp_Stop = datetime.datetime.now()
        Exp_Time = (Time_Exp_Stop - self.Time_Exp_Start).total_seconds()
        if self.stop_trigger == 0 and Exp_Time < self.ExpTimeSetting:
            self.Result_Timestamps = qutag.getLastTimestamps(True)
            data = np.array(self.Result_Timestamps)
            data00 = np.trunc(data[0] / 10)  # / 10)  # * 100
            data11 = data[1]
            length = len(data11)
            threadnumber =5
            threads1 = MyThread(cal,args=(length,0,data00, data11,
                                          self.channel1_cursor1_e, self.channel1_cursor2_e, self.channel1_cursor1_l,
                                          self.channel1_cursor2_l, self.channel1_cursor1_f, self.channel1_cursor2_f,
                                          self.channel2_cursor1_e, self.channel2_cursor2_e, self.channel2_cursor1_l,
                                          self.channel2_cursor2_l, self.channel2_cursor1_f, self.channel2_cursor2_f,
                                          self.channel3_cursor1_e, self.channel3_cursor2_e, self.channel3_cursor1_l,
                                          self.channel3_cursor2_l, self.channel3_cursor1_f, self.channel3_cursor2_f,
                                          self.channel4_cursor1_e, self.channel4_cursor2_e, self.channel4_cursor1_l,
                                          self.channel4_cursor2_l, self.channel4_cursor1_f, self.channel4_cursor2_f))
            threads2 = MyThread(cal, args=(length, 1, data00, data11,
                                           self.channel1_cursor1_e, self.channel1_cursor2_e, self.channel1_cursor1_l,
                                           self.channel1_cursor2_l, self.channel1_cursor1_f, self.channel1_cursor2_f,
                                           self.channel2_cursor1_e, self.channel2_cursor2_e, self.channel2_cursor1_l,
                                           self.channel2_cursor2_l, self.channel2_cursor1_f, self.channel2_cursor2_f,
                                           self.channel3_cursor1_e, self.channel3_cursor2_e, self.channel3_cursor1_l,
                                           self.channel3_cursor2_l, self.channel3_cursor1_f, self.channel3_cursor2_f,
                                           self.channel4_cursor1_e, self.channel4_cursor2_e, self.channel4_cursor1_l,
                                           self.channel4_cursor2_l, self.channel4_cursor1_f, self.channel4_cursor2_f))
            threads3 = MyThread(cal, args=(length, 2, data00, data11,
                                           self.channel1_cursor1_e, self.channel1_cursor2_e, self.channel1_cursor1_l,
                                           self.channel1_cursor2_l, self.channel1_cursor1_f, self.channel1_cursor2_f,
                                           self.channel2_cursor1_e, self.channel2_cursor2_e, self.channel2_cursor1_l,
                                           self.channel2_cursor2_l, self.channel2_cursor1_f, self.channel2_cursor2_f,
                                           self.channel3_cursor1_e, self.channel3_cursor2_e, self.channel3_cursor1_l,
                                           self.channel3_cursor2_l, self.channel3_cursor1_f, self.channel3_cursor2_f,
                                           self.channel4_cursor1_e, self.channel4_cursor2_e, self.channel4_cursor1_l,
                                           self.channel4_cursor2_l, self.channel4_cursor1_f, self.channel4_cursor2_f))
            threads4 = MyThread(cal, args=(length,3, data00, data11,
                                           self.channel1_cursor1_e, self.channel1_cursor2_e, self.channel1_cursor1_l,
                                           self.channel1_cursor2_l, self.channel1_cursor1_f, self.channel1_cursor2_f,
                                           self.channel2_cursor1_e, self.channel2_cursor2_e, self.channel2_cursor1_l,
                                           self.channel2_cursor2_l, self.channel2_cursor1_f, self.channel2_cursor2_f,
                                           self.channel3_cursor1_e, self.channel3_cursor2_e, self.channel3_cursor1_l,
                                           self.channel3_cursor2_l, self.channel3_cursor1_f, self.channel3_cursor2_f,
                                           self.channel4_cursor1_e, self.channel4_cursor2_e, self.channel4_cursor1_l,
                                           self.channel4_cursor2_l, self.channel4_cursor1_f, self.channel4_cursor2_f))
            threads5 = MyThread(cal, args=(length, 4, data00, data11,
                                           self.channel1_cursor1_e, self.channel1_cursor2_e, self.channel1_cursor1_l,
                                           self.channel1_cursor2_l, self.channel1_cursor1_f, self.channel1_cursor2_f,
                                           self.channel2_cursor1_e, self.channel2_cursor2_e, self.channel2_cursor1_l,
                                           self.channel2_cursor2_l, self.channel2_cursor1_f, self.channel2_cursor2_f,
                                           self.channel3_cursor1_e, self.channel3_cursor2_e, self.channel3_cursor1_l,
                                           self.channel3_cursor2_l, self.channel3_cursor1_f, self.channel3_cursor2_f,
                                           self.channel4_cursor1_e, self.channel4_cursor2_e, self.channel4_cursor1_l,
                                           self.channel4_cursor2_l, self.channel4_cursor1_f, self.channel4_cursor2_f))
            threads6 = MyThread(cal, args=(length, 5, data00, data11,
                                           self.channel1_cursor1_e, self.channel1_cursor2_e, self.channel1_cursor1_l,
                                           self.channel1_cursor2_l, self.channel1_cursor1_f, self.channel1_cursor2_f,
                                           self.channel2_cursor1_e, self.channel2_cursor2_e, self.channel2_cursor1_l,
                                           self.channel2_cursor2_l, self.channel2_cursor1_f, self.channel2_cursor2_f,
                                           self.channel3_cursor1_e, self.channel3_cursor2_e, self.channel3_cursor1_l,
                                           self.channel3_cursor2_l, self.channel3_cursor1_f, self.channel3_cursor2_f,
                                           self.channel4_cursor1_e, self.channel4_cursor2_e, self.channel4_cursor1_l,
                                           self.channel4_cursor2_l, self.channel4_cursor1_f, self.channel4_cursor2_f))
            threads7 = MyThread(cal, args=(length, 6, data00, data11,
                                           self.channel1_cursor1_e, self.channel1_cursor2_e, self.channel1_cursor1_l,
                                           self.channel1_cursor2_l, self.channel1_cursor1_f, self.channel1_cursor2_f,
                                           self.channel2_cursor1_e, self.channel2_cursor2_e, self.channel2_cursor1_l,
                                           self.channel2_cursor2_l, self.channel2_cursor1_f, self.channel2_cursor2_f,
                                           self.channel3_cursor1_e, self.channel3_cursor2_e, self.channel3_cursor1_l,
                                           self.channel3_cursor2_l, self.channel3_cursor1_f, self.channel3_cursor2_f,
                                           self.channel4_cursor1_e, self.channel4_cursor2_e, self.channel4_cursor1_l,
                                           self.channel4_cursor2_l, self.channel4_cursor1_f, self.channel4_cursor2_f))
            threads8 = MyThread(cal, args=(length, 7, data00, data11,
                                           self.channel1_cursor1_e, self.channel1_cursor2_e, self.channel1_cursor1_l,
                                           self.channel1_cursor2_l, self.channel1_cursor1_f, self.channel1_cursor2_f,
                                           self.channel2_cursor1_e, self.channel2_cursor2_e, self.channel2_cursor1_l,
                                           self.channel2_cursor2_l, self.channel2_cursor1_f, self.channel2_cursor2_f,
                                           self.channel3_cursor1_e, self.channel3_cursor2_e, self.channel3_cursor1_l,
                                           self.channel3_cursor2_l, self.channel3_cursor1_f, self.channel3_cursor2_f,
                                           self.channel4_cursor1_e, self.channel4_cursor2_e, self.channel4_cursor1_l,
                                           self.channel4_cursor2_l, self.channel4_cursor1_f, self.channel4_cursor2_f))
            threads9 = MyThread(cal, args=(length, 8, data00, data11,
                                           self.channel1_cursor1_e, self.channel1_cursor2_e, self.channel1_cursor1_l,
                                           self.channel1_cursor2_l, self.channel1_cursor1_f, self.channel1_cursor2_f,
                                           self.channel2_cursor1_e, self.channel2_cursor2_e, self.channel2_cursor1_l,
                                           self.channel2_cursor2_l, self.channel2_cursor1_f, self.channel2_cursor2_f,
                                           self.channel3_cursor1_e, self.channel3_cursor2_e, self.channel3_cursor1_l,
                                           self.channel3_cursor2_l, self.channel3_cursor1_f, self.channel3_cursor2_f,
                                           self.channel4_cursor1_e, self.channel4_cursor2_e, self.channel4_cursor1_l,
                                           self.channel4_cursor2_l, self.channel4_cursor1_f, self.channel4_cursor2_f))
            threads10 = MyThread(cal, args=(length, 9, data00, data11,
                                           self.channel1_cursor1_e, self.channel1_cursor2_e, self.channel1_cursor1_l,
                                           self.channel1_cursor2_l, self.channel1_cursor1_f, self.channel1_cursor2_f,
                                           self.channel2_cursor1_e, self.channel2_cursor2_e, self.channel2_cursor1_l,
                                           self.channel2_cursor2_l, self.channel2_cursor1_f, self.channel2_cursor2_f,
                                           self.channel3_cursor1_e, self.channel3_cursor2_e, self.channel3_cursor1_l,
                                           self.channel3_cursor2_l, self.channel3_cursor1_f, self.channel3_cursor2_f,
                                           self.channel4_cursor1_e, self.channel4_cursor2_e, self.channel4_cursor1_l,
                                           self.channel4_cursor2_l, self.channel4_cursor1_f, self.channel4_cursor2_f))
            threads1.start()
           # print('1',datetime.datetime.now())
            threads2.start()
          #  print('2',datetime.datetime.now())
            threads3.start()
          #  print('3', datetime.datetime.now())
            threads4.start()
            threads5.start()
            threads6.start()
            threads7.start()
            threads8.start()
            threads9.start()
            threads10.start()
            threads1.join()
            threads2.join()
            threads3.join()
            threads4.join()
            threads5.join()
            threads6.join()
            threads7.join()
            threads8.join()
            threads9.join()
            threads10.join()
            self.result1 = threads1.get_result()
            self.result2 = threads2.get_result()
            self.result3 = threads3.get_result()
            self.result4 = threads4.get_result()
            self.result5 = threads5.get_result()
            self.result6 = threads6.get_result()
            self.result7 = threads7.get_result()
            self.result8 = threads8.get_result()
            self.result9 = threads9.get_result()
            self.result10 = threads10.get_result()

            self.hist_ch1 = self.hist_ch1+self.result1[-4]+self.result2[-4]+self.result3[-4]+self.result4[-4]+self.result5[-4]+self.result6[-4]+self.result7[-4]+self.result8[-4]+self.result9[-4]+self.result10[-4]
            self.hist_ch2 = self.hist_ch2+self.result1[-3]+self.result2[-3]+self.result3[-3]+self.result4[-3]+self.result5[-3]+self.result6[-3]+self.result7[-3]+self.result8[-3]+self.result9[-3]+self.result10[-3]
            self.hist_ch3 = self.hist_ch3+self.result1[-2]+self.result2[-2]+self.result3[-2]+self.result4[-2]+self.result5[-2]+self.result6[-2]+self.result7[-2]+self.result8[-2]+self.result9[-2]+self.result10[-2]
            self.hist_ch4 = self.hist_ch4+self.result1[-1]+self.result2[-1]+self.result3[-1]+self.result4[-1]+self.result5[-1]+self.result6[-1]+self.result7[-1]+self.result8[-1]+self.result9[-1]+self.result10[-1]
            self.count_sweeps = self.count_sweeps+ self.result1[0]+self.result2[0]+self.result3[0]+self.result4[0]+self.result5[0]+self.result6[0]+self.result7[0]+self.result8[0]+self.result9[0]+self.result10[0]
            self.counts = self.counts + self.result1[1]+self.result2[1]+self.result3[1]+self.result4[1]+self.result5[1]+self.result6[1]+self.result7[1]+self.result8[1]+self.result9[1]+self.result10[1]
            self.coin = self.coin + self.result1[2]+self.result2[2]+self.result3[2]+self.result4[2]+self.result5[2]+self.result6[2]+self.result7[2]+self.result8[2]+self.result9[2]+self.result10[2]
            self.Result_sweeps.setText(str(self.count_sweeps))
            if self.count_sweeps != 0:
                self.pro = np.around(self.counts / self.count_sweeps,5)
            for i in [0, 1, 2,3]:
                for j in [0, 1, 2]:
                    self.Result_Counts.setItem(i, j, QTableWidgetItem(str(self.counts[i][j])))
                    self.Result_Pro.setItem(i, j, QTableWidgetItem(str(self.pro[i][j])))
            for i in [0, 1, 2, 3, 4, 5]:
                for j in [0, 1, 2, 3, 4, 5]:
                    self.Result_Coin.setItem(i, j, QTableWidgetItem(str(self.coin[i][j])+'/'+str(round(self.coin[i][j]/self.count_sweeps*1000,3))))

            # # channel1 data

            # channel1 data
            # if 'self.chart_ch1' in vars() and 'self.series_ch1' in vars():
            #     self.chart_ch1.removeSeries(self.series_ch1)
            #     del self.chart_ch1, self.series_ch1
            #     gc.collect()
            # else:
            #     pass

            self.chart_ch1 = QChart()
            self.chart_ch1.legend().setVisible(False)
            self.Counting_Channel_1.setChart(self.chart_ch1)
            self.series_ch1 = QLineSeries()

            # self.series_ch1.setUseOpenGL(True)
            # self._chart.removeSeries(self.series)
            # self.series.clear()

            # self.series.setName('曲线')
            for i in range(100000):
                self.series_ch1.append(self.hist_ch1[i][0], self.hist_ch1[i][1])
            self.chart_ch1.addSeries(self.series_ch1)
            self.chart_ch1_0 = self.chart_ch1

            self.Counting_Channel_1.setChart(self.chart_ch1)
            self.Counting_Channel_1.setRubberBand(QChartView.HorizontalRubberBand)
            self.axisx = QValueAxis()
            self.axisx.setRange(self.input_chart_range_1_1, self.input_chart_range_1_2)
            self.axisy = QValueAxis()
            # self.axisy.setRange(0, 100)
            self.chart_ch1.setAxisX(self.axisx, self.series_ch1)
            self.chart_ch1.setAxisY(self.axisy, self.series_ch1)

            #
            # channel2 data
            self.chart_ch2 = QChart()
            self.chart_ch2.legend().setVisible(False)
            self.Counting_Channel_2.setChart(self.chart_ch2)
            self.series_ch2 = QLineSeries()
            # self.series_ch2.setUseOpenGL(True)
            for i in range(100000):
                self.series_ch2.append(self.hist_ch2[i][0], self.hist_ch2[i][1])
            self.chart_ch2.addSeries(self.series_ch2)
            self.chart_ch2_0 = self.chart_ch2
            self.Counting_Channel_2.setChart(self.chart_ch2)
            self.Counting_Channel_2.setRubberBand(QChartView.HorizontalRubberBand)
            self.axisx2 = QValueAxis()
            self.axisx2.setRange(self.input_chart_range_2_1, self.input_chart_range_2_2)
            self.axisy2 = QValueAxis()
            # self.axisy2.setRange(-0, 100)
            self.chart_ch2.setAxisX(self.axisx2, self.series_ch2)
            self.chart_ch2.setAxisY(self.axisy2, self.series_ch2)

            # channel3 data
            self.chart_ch3 = QChart()
            self.chart_ch3.legend().setVisible(False)
            self.Counting_Channel_3.setChart(self.chart_ch3)
            self.series_ch3 = QLineSeries()
            # self.series_ch3.setUseOpenGL(True)
            for i in range(100000):
                self.series_ch3.append(self.hist_ch3[i][0], self.hist_ch3[i][1])
            self.chart_ch3.addSeries(self.series_ch3)
            self.chart_ch3_0 = self.chart_ch3
            self.Counting_Channel_3.setChart(self.chart_ch3)
            self.Counting_Channel_3.setRubberBand(QChartView.HorizontalRubberBand)
            self.axisx3 = QValueAxis()
            self.axisx3.setRange(self.input_chart_range_3_1, self.input_chart_range_3_2)
            self.axisy3 = QValueAxis()
            # self.axisy3.setRange(0, 100)
            self.chart_ch3.setAxisX(self.axisx3, self.series_ch3)
            self.chart_ch3.setAxisY(self.axisy3, self.series_ch3)
            # memory_tracker.print_diff()

            self.chart_ch4= QChart()
            self.chart_ch4.legend().setVisible(False)
            self.Counting_Channel_4.setChart(self.chart_ch4)
            self.series_ch4 = QLineSeries()
            # self.series_ch3.setUseOpenGL(True)
            for i in range(100000):
                self.series_ch4.append(self.hist_ch4[i][0], self.hist_ch4[i][1])
            self.chart_ch4.addSeries(self.series_ch4)
            self.chart_ch4_0 = self.chart_ch4
            self.Counting_Channel_4.setChart(self.chart_ch4)
            self.Counting_Channel_4.setRubberBand(QChartView.HorizontalRubberBand)
            self.axisx4 = QValueAxis()
            self.axisx4.setRange(self.input_chart_range_4_1, self.input_chart_range_4_2)
            self.axisy4 = QValueAxis()
            # self.axisy3.setRange(0, 100)
            self.chart_ch4.setAxisX(self.axisx4, self.series_ch4)
            self.chart_ch4.setAxisY(self.axisy4, self.series_ch4)

        else:
            self.Counting_Channel_1.setChart(self.chart_ch1_0)
            self.Counting_Channel_2.setChart(self.chart_ch2_0)
            self.Counting_Channel_3.setChart(self.chart_ch3_0)
            self.Counting_Channel_4.setChart(self.chart_ch4_0)
            # self.Counting_Channel_1.setRubberBand(QChartView.HorizontalRubberBand)
            # self.chart_ch1.setAxisX(self.axisx, self.series_ch1)
            # self.chart_ch1.setAxisY(self.axisy, self.series_ch1)
            self.timer.stop()
            self.stop_trigger = 1
            if self.filewritestop == 0:
                with open(self.filename_result_sum, 'w') as ResultRecording1:
                    ResultRecording1.write('sweeps' + '\t' +
                                           str(self.count_sweeps) + '\n' + 'Channel_counts(Row*Column=channel*timebin)' + '\n')
                    for i in [0, 1, 2, 3]:
                        for j in [0, 1, 2]:
                            ResultRecording1.write(str(self.counts[i][j]) + '\t')
                        ResultRecording1.write('\n')
                    ResultRecording1.write('Coincidence(Row*Column=channel1-2*channel3-4)' + '\n')
                    for i in [0, 1, 2, 3, 4, 5]:
                        for j in [0, 1, 2, 3, 4, 5]:
                            ResultRecording1.write(str(self.coin[i][j]) + '\t')
                        ResultRecording1.write('\n')
                    ResultRecording1.close()

                self.histname_ch1 = self.path + '\DataRecording' + '\hist_ch1.CSV'
                with open(self.histname_ch1, 'w') as f_handle1:
                    np.savetxt(f_handle1, [x for x in self.hist_ch1], delimiter=',')
                    f_handle1.close()
                self.histname_ch2 = self.path + '\DataRecording' + '\hist_ch2.CSV'
                with open(self.histname_ch2, 'w') as f_handle2:
                    np.savetxt(f_handle2, [x for x in self.hist_ch2], delimiter=',')
                    f_handle2.close()
                self.histname_ch3 = self.path + '\DataRecording' + '\hist_ch3.CSV'
                with open(self.histname_ch3, 'w') as f_handle3:
                    np.savetxt(f_handle3, [x for x in self.hist_ch3], delimiter=',')
                    f_handle3.close()
                with open(self.histname_ch4, 'w') as f_handle4:
                    np.savetxt(f_handle4, [x for x in self.hist_ch4], delimiter=',')
                    f_handle4.close()
             #   del self.chart_ch1, self.chart_ch2, self.chart_ch3, self.series_ch1, self.series_ch2, self.series_ch3, f_handle1, f_handle2, f_handle3, ResultRecording1, self.hist_ch1_0, self.hist_ch1_1, self.Result_Timestamps, self.count_sweeps, self.count_channel1, self.count_channel2, self.count_channel3, self.count_coin12, self.count_coin13, self.count_coin23, self.count_coin123, self.count_pro1, self.count_pro2, self.count_pro3, self.count_pro12, self.count_pro13, self.count_pro23, self.count_pro123, self.g12, self.g13, self.g23, self.alpha_1_23, self.g12_err, self.g13_err, self.g23_err, self.alpha_1_23_err, self.histname_ch1, self.histname_ch2, self.histname_ch3, self.timer, self.stop_trigger, self.det2, self.det3, self.Result_Counts_2, self.Result_Counts_3, self.Result_Counts_Coin23, self.hist_ch1, self.hist_ch2, self.hist_ch3
                gc.collect()
                self.filewritestop = 1
                print('stoptime', datetime.datetime.now())
            else:
                pass
            qutag.writeTimestamps('', qutag.FILEFORMAT_NONE)
            sys.stdout.flush()
        # QMessageBox.about(self,"标题","运行结束")


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    app.setStyle("Fusion")
    window = Window()
    window.show()
    sys.exit(app.exec())
